﻿using DzInfo.Model.KD;
using Kingdee.BOS;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.FormService;
using Kingdee.K3.Core.SCM.Args;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Numeric;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.Tools
{
    public static class KDApi
    {
        /// <summary>
        /// 销售订单新变更单接口
        /// </summary>
        /// 
        /// <returns></returns>
        public static XOrderReSult SaveXSaleOrder(string domain, string dataId, string user, string pwd, string saleOrderBillNo, string fid, long[] entryIds)
        {
            //1.构造登陆信息
            //站点地址
            string url = $"http://{domain}/k3cloud/Kingdee.bos.webapi.ServicesStub.authservice.validateuser.common.kdsvc";
            //接口Url地址：POSTMAN调试用
            //string xsUrl = $"http://{domain}/k3cloud/Kingdee.K3.SCM.WebApi.ServicesStub.SaveXSaleOrderWebApi.SaveXSaleOrder.common.kdsvc";

            string dataCenterId = dataId;
            string userName = user;
            string userPwd = pwd;

            //2.登录校验
            var client = new K3CloudApiClient(url);
            var ret = client.ValidateLogin(dataCenterId, userName, userPwd, 2052);
            var jResult = JObject.Parse(ret);
            var resultType = jResult["LoginResultType"].Value<int>();
            if (resultType != 1 && resultType != -5) return null;

            //3.构造生成新变更单参数如下：
            //string parm = "{\"SaleOrderBillNo\":\"XSDD000688\",\"SaleOrderBillId\":100827,\"SOEntryIds\":[102803,102804]}";
            var parm = new
            {
                SaleOrderBillNo = saleOrderBillNo,
                SaleOrderBillId = fid,
                SOEntryIds = entryIds
            };

            //4.客户端调用生成销售订单新变更单接口：
            var result = client.Execute<string>("Kingdee.K3.SCM.WebApi.ServicesStub.SaveXSaleOrderWebApi.SaveXSaleOrder", new object[] { JsonConvert.SerializeObject(parm) });
            var apiRes = JsonConvert.DeserializeObject<XOrderReSult>(result);
            return apiRes;
        }
        /// <summary>
        /// 操作执行API扩展
        /// </summary>
        /// <param name="ctx">上下文</param>
        /// <param name="formId">单据标识</param>
        /// <param name="opNumber">操作代码</param>
        /// <param name="data">接口入参{"CreateOrgId":0,"Numbers":[],"Ids":"","PkEntryIds":[],"UseOrgId":0,"NetworkCtrl":"","IgnoreInterationFlag":""}</param>
        public static ApiResult Execute(Context ctx, string formId, string opNumber, string data)
        {
            var res = JsonConvert.SerializeObject(WebApiServiceCall.Execute(ctx, formId, opNumber, data));
            var apiRes = JsonConvert.DeserializeObject<ApiResult>(res);
            return apiRes;
        }
        /// <summary>
        /// 构造WebApi执行操作入参
        /// </summary>
        /// <param name="numbers"></param>
        /// <param name="ids"></param>
        /// <param name="pkEntryIds"></param>
        /// <returns></returns>
        public static string ExecuteParameter(string numbers, string ids, object[] pkEntryIds)
        {
            var param = new
            {
                Numbers = numbers,
                Ids = ids,
                PkEntryIds = pkEntryIds
            };
            return JsonConvert.SerializeObject(param);
        }
        /// <summary>
        /// 构造WebApi单据查询参数
        /// </summary>
        /// <param name="formId">单据标识</param>
        /// <param name="fieldKeys">查询的字段名</param>
        /// <param name="filterString">查询过滤条件</param>
        /// <returns></returns>
        public static string QueryParameter(string formId, string fieldKeys, string filterString, string orderString, int limit)
        {
            var param = new
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = filterString,
                OrderString = orderString,
                Limit = limit
            };
            return JsonConvert.SerializeObject(param);
        }
        /// <summary>
        /// 扩展云星空单据查询API
        /// </summary>
        /// <param name="ctx">上下文</param>
        /// <param name="formId">单据标识</param>
        /// <param name="fieldKeys">要查询的字段信息</param>
        /// <param name="filterString">过滤条件</param>
        /// <param name="orderString">排序信息</param>
        /// <param name="limit">查询结果的最大行数</param>
        /// <returns></returns>
        public static List<List<object>> ExecuteBillQuery(Context ctx, string formId, string fieldKeys, string filterString, string orderString, int limit)
        {
            var res = WebApiServiceCall.ExecuteBillQuery(ctx, QueryParameter(formId, fieldKeys, filterString, orderString, limit));
            return res;
        }
        /// <summary>
        /// API保存单据
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="formId"></param>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static ApiResult Save(Context ctx, string formId, string jsonStr)
        {
            var _result = JsonConvert.SerializeObject(WebApiServiceCall.Save(ctx, formId, jsonStr));
            JObject result = JObject.Parse(_result);
            var res = JsonConvert.DeserializeObject<ApiResult>(result.ToString());
            return res;
        }
        /// <summary>
        /// API提交单据
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="formId"></param>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static ApiResult Submit(Context ctx, string formId, string jsonStr)
        {
            var _result = JsonConvert.SerializeObject(WebApiServiceCall.Submit(ctx, formId, jsonStr));
            JObject result = JObject.Parse(_result);
            var res = JsonConvert.DeserializeObject<ApiResult>(result.ToString());
            return res;
        }
        /// <summary>
        /// API审核单据
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="formId"></param>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static ApiResult Audit(Context ctx, string formId, string jsonStr)
        {
            var _result = JsonConvert.SerializeObject(WebApiServiceCall.Audit(ctx, formId, jsonStr));
            JObject result = JObject.Parse(_result);
            var res = JsonConvert.DeserializeObject<ApiResult>(result.ToString());
            return res;
        }
        /// <summary>
        /// 变更单生效操作
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="formId"></param>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static ApiResult TakeEffect(Context ctx, string formId, string jsonStr)
        {
            var _result = JsonConvert.SerializeObject(WebApiServiceCall.Execute(ctx, formId, "TakeEffect", jsonStr));
            JObject result = JObject.Parse(_result);
            var res = JsonConvert.DeserializeObject<ApiResult>(result.ToString());
            return res;
        }
    }
}
